<?php
namespace app\common\controller;

use think\Controller;
use think\Log;
use think\Response;
use think\exception\HttpResponseException;

class Base EXTENDS Controller
{
    public function __contruct()
    {
        return '基础方法';
    }

    // 成功时返回数据方法
    public function _success($msg = 'success', $data = null, $code = 200, array $header = []){
    	$this->_result($msg, $data, $code, $header);
    }

    // 发生错误时返回数据方法
    public function _fail($msg = 'false', $data = null, $code = 500, array $header = []){
    	$this->_result($msg, $data, $code, $header);
    }

    /**
     * _result 公共方法 返回请求结果
     * @param  string|array  	$msg    提示说明信息，如果是数组的话需要定义msg data code header 键对应的 key=>value
     * @param  array  			$data   数据
     * @param  integer 			$code   结果代码
     * @param  array   			$header 返回头信息
     * @return json          			返回结果
     */
    protected function _result($msg, $data = null, int $code = 0, array $header = []){
    	// 解决数组形式传参
    	if (is_array($msg)) {
            $msg    = isset($msg['msg']) ? $msg['msg'] : '';
            $data   = isset($msg['data']) ? $msg['data'] : null;
            $code   = isset($msg['code']) ? $msg['code'] : '0000';
            $header = isset($msg['header']) ? $msg['header'] : '';
        }

        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
        ];


        $responseError = $result;

        if(isset($data['rows'])){
            $responseError['data']['rows'] = NULL;
        }

        Log::info(['responseError'=>json_decode(json_encode($responseError), true)]);

        $header['Access-Control-Allow-Origin']  = '*';
        $header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type,XX-Device-Type,XX-Token';
        $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
        $response                               = Response::create($result, 'json')->header($header);
        throw new HttpResponseException($response);
    }




}
